package com.rzico.sbl.ui.report.manager

import android.os.Bundle
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.LegendEntry
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.extend.CustomValueFormatter
import com.github.mikephil.extend.setChartValueSelectedListener
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportStationDetailBinding
import com.rzico.sbl.model.ManagerDate
import com.rzico.sbl.model.ManagerGoodsData
import com.rzico.sbl.other.*
import com.rzico.sbl.viewmodel.ReportStationViewModel
import com.xinnuo.common.extend.formatDecimal
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.getExtra
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.floatValue
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.helper.toFormat
import com.xinnuo.common_ui.base.BaseRootActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadCircleImage

class ReportStationDetailActivity : BaseRootActivity() {

    private lateinit var mBinding: ActivityReportStationDetailBinding

    private lateinit var mMemberId: String
    private val mSaleList = ArrayList<ManagerDate>()
    private var mSaleBeginDate = getBeforeDate(6)
    private var mSaleEndDate = getTodayDate()

    private val mGoodsList = ArrayList<ManagerGoodsData>()
    private val mRangeList = ArrayList<ManagerDate>()
    private var mProductSn = ""
    private var mGoodsBeginDate = getBeforeDate(6)
    private var mGoodsEndDate = getTodayDate()

    override fun getViewModel() = get<ReportStationViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mBinding = ActivityReportStationDetailBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        transparentStatusBar()

        initListener()
        initData()

        getSaleData()
        getBrandData()
    }

    /**
     * 监听方法
     */
    override fun initListener() {
        mMemberId = intent.getExtra("memberId")

        mBinding.apply {
            stationSaleTime.addTimeListener { start, end, _ ->
                mSaleBeginDate = start
                mSaleEndDate = end

                getViewModel().cancelRequest()
                getSaleData()
            }

            stationGoodsTime.addTimeListener { start, end, _ ->
                mGoodsBeginDate = start
                mGoodsEndDate = end

                getViewModel().cancelRequest()
                getBrandData()
            }
        }
    }

    /**
     * 初始化控件
     */
    override fun initData() {
        mBinding.also {
            it.stationSale.apply {
                initChart(
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f,
                    xSpaceEntry = 50f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mSaleList.indices) ""
                    else mSaleList[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }

                // 自定义图例数据
                legend.setCustom(
                    arrayOf(
                        LegendEntry(
                            "销量",
                            Legend.LegendForm.DEFAULT,
                            Float.NaN,
                            Float.NaN,
                            null,
                            getViewModel().color2()[0]
                        ),
                        LegendEntry(
                            "低于100",
                            Legend.LegendForm.DEFAULT,
                            Float.NaN,
                            Float.NaN,
                            null,
                            getViewModel().color2()[1]
                        )
                    )
                )
            }

            it.stationMoney.apply {
                initChart(
                    xLabelAngle = -45f,
                    xSpaceRatio = 0.3f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mSaleList.indices) ""
                    else mSaleList[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.stationGoods.apply {
                initChart(
                    isLegend = false,
                    touchDistance = 10f,
                    xLabelAngle = -45f,
                    xTextSize = 8f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mGoodsList.indices) ""
                    else mGoodsList[value.toInt()].name
                }

                // 添加点击事件
                setChartValueSelectedListener {
                    onValueSelected { entry, _ ->
                        val index = entry.x.toInt()

                        mProductSn = mGoodsList[index].sn
                        mBinding.stationGoodsTitle.text = mGoodsList[index].name
                        getRangeData()
                    }
                }
            }

            it.stationNear.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mRangeList.indices) ""
                    else mRangeList[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.stationImg.loadCircleImage(intent.getExtra("logo"))
            it.stationName.text = intent.getExtra("name")
            it.stationPhone.text = intent.getExtra("phone")

            intent.getExtra("title").apply {
                it.stationTitle.text = this
                it.stationTitle2.text = this
            }
        }
    }

    /**
     * 设置所有商品销量柱状图数据
     */
    private fun setBrandData() {
        mGoodsList.sumOf {
            it.quantity.intValue
        }.apply {
            mBinding
                .stationGoodsTotal
                .text = if (this > 0) " (总: ${this})" else ""
        }

        mBinding
            .stationGoods
            .apply {
                if (mGoodsList.isEmpty()) {
                    clear()
                    mBinding.stationNear.clear()
                    mBinding.stationGoodsTitle.text = "暂无商品"
                } else {
                    setSingleData(
                        entries = mGoodsList.mapIndexed { index, data ->
                            BarEntry(index.toFloat(), data.quantity.toFloat())
                        },
                        colorList = getViewModel().brandColor(),
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
    }

    /**
     * 设置单个商品销量柱状图数据
     */
    private fun setGoodsData() {
        mBinding
            .stationNear
            .apply {
                setSingleData(
                    entries = mRangeList.mapIndexed { index, data ->
                        BarEntry(index.toFloat(), data.quantity.toFloat())
                    },
                    colorList = listOf(
                        getViewModel()
                            .brandColor()[
                                mGoodsList.indexOfFirst { it.sn == mProductSn } % 24
                            ]
                    ),
                    isHighlight = false,
                    formatter = CustomValueFormatter()
                )

                animateY(500)
            }
    }

    /**
     * 设置销量、金额图表数据
     */
    private fun setSaleChartData() {
        mBinding.also { binding ->
            mSaleList.sumOf {
                it.quantity.intValue
            }.apply {
                binding
                    .stationSaleTotal
                    .text = if (this > 0) " (总: ${this})" else ""
            }

            mSaleList.sumOf {
                it.amount.doubleValue
            }.apply {
                binding
                    .stationMoneyTotal
                    .text = if (this != 0.0) " (总: ${this.formatDecimal()})" else ""
            }

            binding
                .stationSale
                .apply {
                    if (mSaleList.none { it.quantity.intValue > 0 }) clear()
                    else {
                        getViewModel()
                            .initSaleBarData(
                                barChart = this,
                                entries = mSaleList.mapIndexed { index, data ->
                                    BarEntry(index.toFloat(), data.quantity.toFloat())
                                }
                            )
                    }

                    animateY(500)
                }

            binding
                .stationMoney
                .apply {
                    if (mSaleList.none { it.amount.doubleValue != 0.0 }) clear()
                    else {
                        setSingleData(
                            entries = mSaleList.mapIndexed { index, data ->
                                Entry(index.toFloat(), data.amount.floatValue)
                            },
                            lineMode = "linear",
                            lineSize = 0f,
                            isDrawCircles = false,
                            drawableFill = R.drawable.fade_station_money,
                            formatter = CustomValueFormatter()
                        )
                    }

                    animateY(500)
                }
        }
    }

    /**
     * 获取销量、金额图表数据
     */
    private fun getSaleData() {
        getViewModel()
            .amountList(
                memberId = mMemberId,
                beginDate = mSaleBeginDate,
                endDate = mSaleEndDate,
                onSuccess = {
                    mSaleList.clear()
                    mSaleList.addItems(it)

                    setSaleChartData()
                }
            )
    }

    /**
     * 获取所有商品销量
     */
    private fun getBrandData() {
        getViewModel()
            .goodsBrandList(
                memberId = mMemberId,
                beginDate = mGoodsBeginDate,
                endDate = mGoodsEndDate,
                onSuccess = { list ->
                    mGoodsList.clear()
                    mGoodsList.addItems(list)

                    setBrandData()

                    if (mGoodsList.isNotEmpty()) {
                        if (mGoodsList.none { it.sn == mProductSn }) {
                            mProductSn = mGoodsList[0].sn
                            mBinding.stationGoodsTitle.text = mGoodsList[0].name
                        }
                        getRangeData()
                    }
                }
            )
    }

    /**
     * 获取单个商品最近销量
     */
    private fun getRangeData() {
        getViewModel()
            .goodsSaleList(
                goodsSn = mProductSn,
                memberId = mMemberId,
                beginDate = mGoodsBeginDate,
                endDate = mGoodsEndDate,
                onSuccess = {
                    mRangeList.clear()
                    mRangeList.addItems(it)

                    setGoodsData()
                }
            )
    }

}